<template>
  <div class="app-container">
    <div class="search-area">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item  class="input_st"  label="是否是会员" label-width="100" prop="isMember">
        <el-select v-model="queryParams.isMember" placeholder="请选择是否是会员" clearable>
          <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item  class="input_st"  label="支付方式" prop="method">
        <el-select v-model="queryParams.method" placeholder="请选择支付方式" clearable>
          <el-option
              v-for="dict in method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" >
        <el-date-picker
            v-model="daterangeCreateTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="getDateStr()"

        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="Download"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['system:order:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div v-if="orderList.length===0" class="empty-container">
      <el-empty description="暂无会员数据" />
    </div>
    <div v-else class="table-container">
    <el-table  height="500"
               v-loading="loading"
               element-loading-text="数据正在加载中,请稍后......"
               element-loading-svg-view-box="-10, -10, 50, 50"
               element-loading-background="rgba(122, 122, 122, 0.8)"
               border  show-summary
               :summary-method="getSummaries"
               :data="orderList"
               @selection-change="handleSelectionChange"
               class="custom-table"
               row-key="id"
               :row-class-name="tableRowClassName"
               :default-expand-all="false"
               @expand-change="handelCell"
               style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand" width="100" label="展开行/详情">
        <template #default="props">
          <!-- 只对会员行渲染展开内容 -->
          <template v-if="props.row.isMember === 'Y'">
            <el-card class="member-detail-card" shadow="hover" style="margin: 16px;">
              <div slot="header" class="flex justify-between items-center">
                <h3 class="font-bold text-lg">会员详细信息</h3>
                <span class="text-sm" v-if="formInline.createTime">
            创建时间: {{ formInline.createTime|| '-' }}
          </span>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-6 p-4">
                <!-- 基本信息组 -->
                <div>
                  <h4 class="text-sm text-gray-500 mb-3">基本信息</h4>
                  <el-descriptions column="1" border>
                    <el-descriptions-item label="姓名">{{ formInline.fullName || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="电话">{{ formInline.phone || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="性别">
                      <dict-tag :options="sys_user_sex" :value="formInline.gender"/>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>

                <!-- 会员信息组 -->
                <div>
                  <h4 class="text-sm text-gray-500 mb-3">会员信息</h4>
                  <el-descriptions column="1" border>
                    <el-descriptions-item label="积分余额">
                      {{ formInline.pointsBalance || 0 }}
                    </el-descriptions-item>
                    <el-descriptions-item label="状态">
                      <dict-tag :options="m_status" :value="formInline.status"/>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>

              <!-- 备注信息 -->
              <div class="mt-4 p-4 border-t">
                <h4 class="text-sm text-gray-500 mb-2">备注</h4>
                <div class="bg-gray-50 p-3 rounded text-sm">
                  {{ formInline.remark || '无备注信息' }}
                </div>
              </div>
            </el-card>
          </template>

          <!-- 非会员行显示提示信息 -->
          <template v-else>
            <div style="padding: 20px; text-align: center; color: #999;">
              <el-icon class="mr-2"><InfoFilled /></el-icon>
              非会员行无详细信息
            </div>
          </template>
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号 " width="60" align="center"   :index="indexMethod" />
      <el-table-column label="是否是会员" align="center" sortable prop="isMember">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isMember"/>
        </template>
      </el-table-column>
      <el-table-column label="收款金额" sortable align="center" prop="price" >
        <template #default="scope">
          ￥{{scope.row.price}}
        </template>
      </el-table-column>
      <el-table-column label="创建日期" sortable align="center" prop="createTime" width="170">
        <template #default="scope">
          <span><el-icon><timer /></el-icon>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}  {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" sortable align="center" prop="updateTime" width="170">
        <template #default="scope">
          <span><el-icon><timer /></el-icon>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}  {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="支付方式" sortable align="center" prop="method">
        <template #default="scope">
          <dict-tag :options="method" :value="scope.row.method"/>
        </template>
      </el-table-column>
      <el-table-column label="备注信息"  align="center" prop="remark" sortable  show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-hasPermi="['system:members:remove']">
        <template #default="scope">
          <el-button link type="warning" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:order:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog draggable destroy-on-close center
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="title"
               v-model="open"
               width="500px"
               append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="是否是会员" label-width="100" prop="isMember">
          <el-radio-group v-model="form.isMember">
            <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收款金额" prop="price">
          <el-input-number :min="0" :step="0.5"  v-model="form.price" placeholder="请输入收款金额" />
        </el-form-item>
        <el-form-item label="支付方式" prop="method">
          <el-radio-group v-model="form.method">
            <!-- 会员时禁用现金、微信、支付宝 -->
            <el-radio
                v-for="dict in method"
                :key="dict.value"
                :label="dict.value"
                :disabled="
  (form.isMember === 'Y' && ['1', '2'].includes(dict.value)) ||
  (form.isMember === 'N' && dict.value === '3')
"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/system/orders"
import {getMembers} from "../../../api/system/members/index.js";
import {getDateStr,indexMethod,tableRowClassName} from "@/utils/ruoyi.js"
const { proxy } = getCurrentInstance()
const { m_status, sys_user_sex, sys_yes_no, method  } = proxy.useDict('m_status', 'sys_user_sex','method','sys_yes_no')
const orderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 格式化日期时间为 "YYYY-MM-DD HH:mm:ss" 格式
const formatDateTime = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取当前日期
const today = new Date();

// 当天00:00:00
const startOfDay = new Date(today);
startOfDay.setHours(0, 0, 0, 0);

// 当天23:59:59
const endOfDay = new Date(today);
endOfDay.setHours(23, 59, 59, 999);

// 设置默认时间范围为当天0点到23点59分59秒
const daterangeCreateTime = ref([
  formatDateTime(startOfDay),
  formatDateTime(endOfDay)
]);
const data = reactive({
  formInline:{
  },
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    id: null,
    isMember: null,
    price: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    delFlag: null,
    method: null
  },
  rules: {
    id: [
      { required: true, message: "主键id不能为空", trigger: "blur" }
    ],
    isMember: [
      { required: true, message: "是否是会员不能为空", trigger: "change" }
    ],
    price: [
      { required: true, message: "收款金额不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建日期不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "修改日期不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
    updateBy: [
      { required: true, message: "修改人不能为空", trigger: "blur" }
    ],
    delFlag: [
      { required: true, message: "删除标记不能为空", trigger: "blur" }
    ],
    method: [
      { required: true, message: "支付方式不能为空", trigger: "change" }
    ]
  }
})


const { queryParams, form, rules,formInline } = toRefs(data)
const handelCell=(row,expandedRows)=>{
  formInline.value={};
  if (expandedRows.length>0) {
    if (row.mid!=null){
      getMembers(row.mid).then(res=>{
        if (res.code===200){
          formInline.value=res.data;
        }else {
          formInline.value={};
        }
      })
    }

  }
}
/** 查询订单列表 */
function getList() {
  orderList.value=[];
  loading.value = true

  if (null != daterangeCreateTime.value) {
    queryParams.value.beginCreateTime = daterangeCreateTime.value[0]
    queryParams.value.endCreateTime = daterangeCreateTime.value[1]
  }else {
    queryParams.value.beginCreateTime = null
    queryParams.value.endCreateTime = null
  }
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false

  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    isMember: null,
    price: 0,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    delFlag: null,
    method: null,
    remark: null,
  }
  proxy.resetForm("orderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改订单"
  })
}
// 自定义合计方法 - 只计算收款金额
const getSummaries = ({ columns, data }) => {
  const sums = [];

  columns.forEach((column, index) => {
    // 第一列显示"合计"
    if (index === 0) {
      sums[index] = '合计';
      return;
    }

    // 只对收款金额列(prop为price)进行求和计算
    if (column.property === 'price') {
      // 计算总和
      const total = data.reduce((sum, item) => {
        const price = Number(item.price) || 0;
        return sum + price;
      }, 0);

      // 格式化显示
      sums[index] = `￥${total.toFixed(0)}`;
    } else {
      // 其他列不计算，留空
      sums[index] = '';
    }
  });

  return sums;
};

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}
getList()
</script>
<style scoped>

/* 整体布局样式 */
.app-container {
  padding: 20px;
  background-color: #f5f7f9;

}

/* 搜索区域样式 */
.search-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

.custom-form {
  display: flex;
  flex-wrap: wrap;
  gap: 9px;
  align-items: flex-start;
}

.custom-form :deep(.el-form-item) {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.custom-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  width: 80px;
  text-align: right;
  flex-shrink: 0;
}

.custom-form :deep(.el-form-item__content) {
  flex: 1;
  min-width: 0;
}

.input_st {
  width: 230px;
  flex-shrink: 0;
}

.date-range-item {
  width: 425px;
}

.form-buttons {
  margin-left: auto;
  align-self: center;
  flex-shrink: 0;
}

/* 操作按钮区域样式 */
.operation-bar {
  background: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

/* 表格容器样式 */
.table-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 15px;
}

/* 表格样式 */
.custom-table {
  border-radius: 4px;
  overflow: hidden;
}

.custom-table :deep(th) {
  background-color: #f8f9fa !important;
  color: #495057;
  font-weight: 600;
  height: 50px;
}

.custom-table :deep(td) {
  padding: 12px 0;
  height: 54px;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.custom-table :deep(.el-table__row--striped) {
  background-color: #fafafa;
}

.custom-table :deep(.el-table__row--striped:hover) {
  background-color: #f5f7fa;
}

/* 隐藏表格滚动条 */
.table-container :deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 0 !important;
  height: 0 !important;
  display: none;
}

.table-container :deep(.el-table__body-wrapper) {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 空数据样式 */
.empty-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 40px 0;
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

/* 分页样式 */
.custom-pagination {
  background: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: flex-end;
}

/* 对话框样式 */
.custom-dialog :deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  margin-right: 0;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 30px 20px;
}

.custom-dialog :deep(.el-form-item) {
  margin-bottom: 22px;
}

.custom-dialog :deep(.el-input__inner) {
  height: 38px;
  line-height: 38px;
}

.custom-dialog :deep(.el-textarea__inner) {
  min-height: 80px;
}

.dialog-footer {
  padding-top: 10px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 1400px) {
  .input_st {
    width: 180px;
  }

  .date-range-item {
    width: 350px;
  }
}

@media (max-width: 1200px) {
  .input_st {
    width: 160px;
  }

  .date-range-item {
    width: 320px;
  }
}

@media (max-width: 992px) {
  .custom-form {
    flex-direction: column;
    align-items: stretch;
  }

  .input_st, .date-range-item {
    width: 100%;
  }

  .form-buttons {
    margin-left: 0;
    align-self: flex-start;
  }

  .custom-form :deep(.el-form-item) {
    flex-direction: column;
    align-items: flex-start;
  }

  .custom-form :deep(.el-form-item__label) {
    width: 100%;
    text-align: left;
    margin-bottom: 8px;
  }
}

.el-table /deep/ .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table /deep/ .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
/* 渐变边框 */
.el-input__inner{
  border-image:linear-gradient(to right,#000718,#23b7cb) 5 5!important;
  /* 自定义其他样式时 注意加 !important 安全一些 */
}
/* 可以自定义合计行样式 */
::v-deep .el-table__footer-wrapper {
  font-weight: bold;
}

::v-deep .el-table__footer-wrapper td {
  background-color: #f5f7fa;
}
/* 非会员行隐藏展开图标 */
.el-table__row:not(.is-member) .el-table__expand-icon {
  display: none;
}
</style>
